dict1 = {'name': 'TOM', 'age': 20, 'gender': '男'}

# 1. [key]
# print(dict1['name'])  # 返回对应的值(key存在) TOM
"""
python-BaseException
Traceback (most recent call last):
  File "D:\program files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1570, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\program files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "E:\Python1和2编程（课件和源码）\代码\04-数据序列\04-字典\hm_05_字典常用操作之查找数据.py", line 5, in <module>
    print(dict1['names'])
          ~~~~~^^^^^^^^^
KeyError: 'names'
"""

# print(dict1['names'])

# 2. 函数
# 2.1 get()
print(dict1.get('name')) #TOM
print(dict1.get('names'))  #None 如果key不存在，返回None
print(dict1.get('names', 'Lily')) #Lily

# 2.2 keys() 查找字典中所有的key，返回可迭代对象
print(dict1.keys()) #dict_keys(['name', 'age', 'gender'])

# 2.3 values() 查找字典中的所有的value，返回可迭代对象
print(dict1.values())#dict_values(['TOM', 20, '男'])


# 2.4 items() 查找字典中所有的键值对，返回可迭代对象，里面的数据是元组，元组数据1是字典的key，元组数据2是字典key对应的值
print(dict1.items()) #dict_items([('name', 'TOM'), ('age', 20), ('gender', '男')])

